package com.example.ruiji.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.ruiji.common.Result;
import com.example.ruiji.entity.Category;
import com.example.ruiji.entity.Dish;
import com.example.ruiji.entity.Setmeal;
import com.example.ruiji.mapper.CategoryMapper;
import com.example.ruiji.mapper.DishMapper;
import com.example.ruiji.mapper.SetmealMapper;
import com.example.ruiji.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    @Override
    public Result<Page<Category>> Page(Integer page, Integer pageSize) {
        Page<Category> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByAsc(Category::getSort);
        Page<Category> categoryPage = categoryMapper.selectPage(pageInfo, lambdaQueryWrapper);
        return Result.success(categoryPage);
    }

    @Override
    public Result<String> add(Category category) {
        categoryMapper.insert(category);
        return Result.success("新增分类成功");
    }

    @Override
    public Result<String> delete(Long id) {
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(Dish::getCategoryId, id);
        Integer dishCount = dishMapper.selectCount(dishLambdaQueryWrapper);

        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId, id);
        Integer setMealCount = setmealMapper.selectCount(setmealLambdaQueryWrapper);

        if (dishCount > 0 || setMealCount > 0) {
            return Result.error("当前分类下关联了菜品，不能删除");
        }
        categoryMapper.deleteById(id);
        return Result.success("删除分类成功");
    }

    @Override
    public Result<String> update(Category category) {
        categoryMapper.updateById(category);
        return Result.success("修改成功");
    }

    @Override
    public Result<List<Category>> getCategories(Category category) {
        LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(category.getType() != null, Category::getType, category.getType());
        lambdaQueryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> categories = categoryMapper.selectList(lambdaQueryWrapper);
        return Result.success(categories);
    }
}
